package EP1.algoritmos.algoritmo1;

import java.util.ArrayList;

public class Algoritmo1 implements Runnable {

    private int inicio;
    private int fim;
    
    public static float sum;

    public Algoritmo1(int inicio, int fim) {
	this.inicio = inicio;
	this.fim = fim;
    }

    public static float calculaSoma(int cores, int n) {
	sum = 0;

	int divisao = n / cores;

	int inicio;
	int fim;

	ArrayList<Thread> threads = new ArrayList<Thread>();

	if (cores > 1) {
	    int i;
	    for (i = 0; i < cores - 1; i++) {
		inicio = (i * divisao) + 1;
		fim = (i * divisao) + divisao;
		threads.add(new Thread(new Algoritmo1(inicio, fim)));
	    }

	    inicio = (i * divisao) + 1;
	    fim = n;
	    threads.add(new Thread(new Algoritmo1(inicio, fim)));
	}

	else {
	    threads.add(new Thread(new Algoritmo1(1, n)));
	}

	for (Thread t : threads) {
	    t.start();
	}

	// Espera todas as somas terminarem
	for (Thread t : threads) {
	    try {
		t.join();
	    } catch (InterruptedException e) {
	    }
	}

	return sum;
    }

    @Override
    public void run() {
	float parcial = 0;
	for (int i = inicio; i <= fim; i++) {
	    parcial += (1.0 / (i * i));
	}
	add(parcial);
    }

    public synchronized void add(float f){
	sum += f;
    }
}
